package
{
	import as3isolib.geom.Pt;
	
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	import flash.geom.Point;
	import flash.geom.Vector3D;

	public class GMDefault implements IGameMode
	{
		private var m_mouseDown:Boolean = false;
		private var m_oldMousePoint:Point;
		private var m_moveStoreHelper:MoveGameObjectHelper;
		private var m_mouseWasDragging:Boolean = false;
		private var m_highlightFilter:GlowFilter = new GlowFilter(0x00ffff, .5);
		private var m_selectedStore:GameObject;
		
		public function GMDefault()
		{
			m_moveStoreHelper = new MoveGameObjectHelper();
		}
		
		public function onMouseDown(me:MouseEvent):void{
		}
		
		public function onMouseUp(me:MouseEvent):void{
				if(m_moveStoreHelper.isInMovementMode()){
					m_moveStoreHelper.endMove();
				} else {
					if(m_selectedStore){
						m_moveStoreHelper.startMove(m_selectedStore);
					}	
				}	
		}
		
		public function onMouseMove(me:MouseEvent):void{
			var mouseIsDragging:Boolean = m_mouseDown;
			var currentPosition:Point = new Point(me.stageX, me.stageY);
			var isoPosition:Pt = Global.isoView.localToIso(currentPosition);
			
			if(mouseIsDragging){
				m_mouseWasDragging = true;
				var deltaPosition:Point = m_oldMousePoint.subtract(currentPosition);
				Global.isoView.panBy(deltaPosition.x, deltaPosition.y);
			} else {
				m_mouseWasDragging = false;
				if(m_moveStoreHelper.isInMovementMode()){
					m_moveStoreHelper.updateMovePosition(new Vector3D(isoPosition.x, isoPosition.y, 0));
				} else {
					testForSelectedStore(currentPosition, isoPosition);
				}
			}
			
			m_oldMousePoint = currentPosition.clone();
		}
		
		private function testForSelectedStore(currentPosition:Point, isoPosition:Pt):void{
			var storesMousedOver:Vector.<GameObject> = new Vector.<GameObject>;
			var selectedStore:GameObject;
			var minDistance:Number = Number.MAX_VALUE;
			
			for (var i:int=0, l:int = Global.stores.length; i < l; i++){
				var store:GameObject = Global.stores[i];
				store.isoDisplay.container.filters = [];
				if(store.isoDisplay.container.hitTestPoint(currentPosition.x, currentPosition.y,true)){
					storesMousedOver.push(store);
				}
			}			
			
			for(i=0, l=storesMousedOver.length; i < l; i++){
				store = storesMousedOver[i];
				var basePoint:Point = new Point(store.isoDisplay.x + Constants.SQUARE_SIZE, store.isoDisplay.y + Constants.SQUARE_SIZE);
				var distance:Number = basePoint.subtract(isoPosition).length;
				if(distance < minDistance){
					selectedStore = store;
					minDistance = distance;						
				}
			}
			
			if(selectedStore){
				selectedStore.isoDisplay.container.filters = [m_highlightFilter];
				m_selectedStore = selectedStore;
			} else {
				m_selectedStore = null;
			}						
		}				
	}
}